package com.shopx.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
public class CmdUtil {
    public static String runShell (String shStr){
        Process process = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        String line = "" ;
        String result = "" ;
        try{
            process = Runtime.getRuntime().exec( new String[]{ "/bin/sh" , "-c" ,shStr});
            process.waitFor();
            BufferedReader read = new BufferedReader( new InputStreamReader(process.getInputStream()));
            while ((line = read.readLine())!= null ){
                result+=line+"\n";
            }
            return result;
        }catch (Exception e){
            log.error("exec.shell.error");
        }finally {
            if(process!=null){
                process.destroy();
            }
            if(br!=null){
                try {
                    br.close();
                }catch (Exception e){
                    log.error("runShell.br.close.error");
                }
            }
            if(isr!=null){
                try {
                    isr.close();
                }catch (Exception e){
                    log.error("runShell.isr.close.error");
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String command = "cd /Volumes/DEV/syncfile;grep -r '15200824220|shad|10692215876109' send_cache_20230505.txt" ;
        String s = CmdUtil.runShell(command);
        System.out.println(s);
    }
}
